package com.nikitova.utils.data
{

	/**
	 * @author schranz
	 */
	import flash.system.Capabilities;

	public class PathUtils 
	{

		/**
		 * split a querystring into an object
		 */
		public static function splitURI( uri:String ):Object
		{
			var querystrPos:Number = uri.lastIndexOf( "?" );
			querystrPos = querystrPos == -1 ? uri.length : querystrPos;
			var querystring:String = uri.substring( querystrPos + 1, uri.length );
			var filename:String = uri.substring( 0, querystrPos );

			var params:Array = querystring.split( "&" );
			var length:Number = params.length;
			var parameters:Object = new Object( );
			
			for (var i:Number = 0, index:Number = -1; i < length ; i++) 
			{
				var kvPair:String = params[i];
				if((index = kvPair.indexOf( "=" )) > 0)
				{
					var key:String = kvPair.substring( 0, index );
					var value:String = kvPair.substring( index + 1 );
					
					parameters[key] = value;
				}
			}

			return { filename: filename, parameters: parameters };
		}

		/**
		 * creates a querystring from a uri object
		 */
		public static function combineURI( o:Object ):String
		{
			var ret:String = o.filename;
			if (typeof(o.parameters) == "object")
			{
				ret += "?";
				var x:Array = new Array( );
				for (var i:String in o.parameters)
				{
					x.push( i + "=" + o.parameters[i] );
				}
				ret += x.join( "&" );
			} 

			return ret; 
		}

		/**
		 * are we running on a server?
		 */
		public static function isRunningLocal():Boolean
		{
			return (Capabilities.playerType == "External" || Capabilities.playerType == "StandAlone");
		}

		/**
		 * format the URI
		 */
		public static function formatURI( uri:String, params:Object ):String
		{
			var o:Object = splitURI( uri );
			var ret:String = "";
			
			if (isRunningLocal())
			{
				ret += o.filename;
				return ret;
			}
			else
			{
				for (var i:String in params)
				{
					o.parameters[i] = params[i];
				}
				ret = combineURI( o );
				return ret;
			}
		}
	}
}
